package com.cym.config;

import java.io.File;

import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.config.annotation.CorsRegistry;
import org.springframework.web.servlet.config.annotation.InterceptorRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;

import cn.hutool.core.util.RuntimeUtil;
import jakarta.annotation.PostConstruct;
import jakarta.annotation.Resource;

@Configuration
public class WebConfig implements WebMvcConfigurer {
	@Resource
	private CommonInterceptor commonInterceptor;

	@Value("${spring.profiles.active}")
	String active;

	/**
	 * 跨域配置
	 */
	@Override
	public void addCorsMappings(CorsRegistry registry) {
		registry.addMapping("/**")//
				.allowedOriginPatterns("*")//
				.allowedMethods("POST", "GET", "OPTIONS")//
				.maxAge(3600)//
				.allowCredentials(true);//
	}

	/**
	 * 拦截器
	 */
	@Override
	public void addInterceptors(InterceptorRegistry registry) {

		registry.addInterceptor(commonInterceptor).addPathPatterns("/**") //
				.excludePathPatterns("/api/**")//
				.excludePathPatterns("/css/**")//
				.excludePathPatterns("/img/**")//
				.excludePathPatterns("/js/**")//
				.excludePathPatterns("/lib/**")//
				.excludePathPatterns("robots.txt")//
		;

	}

	/**
	 * 重启nginx
	 */
	@PostConstruct
	public void init() {
		if (active.equals("prod")) {
			RuntimeUtil.exec("cmd", "/c", "taskill /im nginx.exe /f");
			RuntimeUtil.exec(null, new File("E:\\nginx"), "cmd", "/c", "nginx.exe");
		}
	}

}
